<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <style>
        /* 购物车样式 */
        /* 新增表格样式 */
        .cart-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .cart-table tr{
            border-bottom: 1px solid #eee;
        }


        .cart-table thead {
            background: #f8f9fa;
            font-weight: 600;
        }

        .cart-table th {
            padding: 15px;
            text-align: left;
            border-bottom: 2px solid #eee;
        }

        .cart-table td {
            padding: 15px;
            vertical-align: middle;
            height: 162px;
        }

        .item-thumbnail {
            width: 80px;
            height: 80px;
            margin-right: 10px;
            object-fit: contain;
        }

        .quantity-selector {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .item-actions {
            text-align: right;
            padding-left: 20px;
        }

        .remove-btn {
            background: none;
            border: none;
            color: #e4393c;
            font-size: 1.2em;
            cursor: pointer;
        }

        /* 响应式优化 */
        @media (max-width: 768px) {
            .cart-table {
                display: block;
                overflow-x: auto;
            }

            .cart-table td {
                white-space: nowrap;
            }
        }
        .cart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #eee;
        }

        .clear-cart-btn {
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
        }

        .clear-cart-btn:hover {
            color: #e4393c;
        }

        .cart-items {
            padding: 20px;
        }

        .cart-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .item-checkbox {
            width: 30px;
        }

        .item-image {
            width: 100px;
            height: 100px;
            margin-right: 15px;
        }

        .item-image img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .item-info {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .item-info h3 {
            margin: 0 0 10px 0;
            font-size: 16px;
            font-weight: normal;
        }

        .item-price {
            color: #e4393c;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .quantity-selector {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .quantity-selector button {
            width: 30px;
            height: 30px;
            border: 1px solid #ddd;
            background-color: #f9f9f9;
            cursor: pointer;
        }

        .quantity-selector input {
            width: 50px;
            height: 30px;
            text-align: center;
            border: 1px solid #ddd;
            border-left: none;
            border-right: none;
        }

        .remove-btn {
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            text-align: left;
            padding: 0;
            width: fit-content;
        }

        .remove-btn:hover {
            color: #e4393c;
        }

        .item-subtotal {
            width: 120px;
            text-align: right;
        }

        .item-subtotal.price {
            color: #e4393c;
            font-weight: bold;
        }

        .cart-summary {
            position: fixed;
            bottom: 50px;
            left: 0;
            right: 0;
            background-color: white;
            border-top: 1px solid #ddd;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .total-price.price {
            color: #e4393c;
            font-size: 18px;
            font-weight: bold;
        }

        .checkout-btn {
            background-color: #e4393c;
            color: white;
            border: none;
            padding: 10px 30px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        .checkout-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .empty-cart {
            text-align: center;
            padding: 50px 0;
        }

        .empty-cart i {
            font-size: 60px;
            color: #ccc;
            margin-bottom: 20px;
            display: block;
        }

        .start-shopping-btn {
            background-color: #e4393c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div id="cart-page" v-if="cartItems.length > 0">
    <div class="cart-header">
        <h2>我的购物车</h2>
    </div>
    <!-- 新增表头 -->
    <table class="cart-table">
        <thead>
        <tr>
            <th>商品</th>
            <th>单价</th>
            <th>数量</th>
            <th>小计</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in cartItems" :key="item.cartId">
            <td class="item-info">
                <img :src="item.imageUrl" alt="商品图片" class="item-thumbnail" @click="goToProductDetail(item.productId)">
                <div>
                    <h3>{{ item.productName }}</h3>
                    <p>库存：{{ item.stock }}</p>
                </div>
            </td>
            <td class="item-price">¥{{ item.price.toFixed(2) }}</td>
            <td class="quantity-selector">
                <button @click="decreaseQuantity(index)" :disabled="item.quantity <= 1">-</button>
                <input type="number" v-model="item.quantity" min="1">
                <button @click="increaseQuantity(index)">+</button>
            </td>
            <td class="item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</td>
            <td class="item-actions">
                <input type="checkbox" v-model="item.selected">
                <button @click="removeFromCart(item.productId)" class="remove-btn">删除</button>
            </td>
        </tr>
        </tbody>
    </table>
    <div class="cart-summary">
        <div class="selected-count">
            已选择 <span>{{ selectedCount }}</span> 件商品
        </div>
        <div class="total-price">
            总价: <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <button @click="checkout" class="checkout-btn" :disabled="selectedCount === 0">
            结算 ({{ selectedCount }})
        </button>
    </div>
</div>
<div v-else class="empty-cart">
    <i class="el-icon-shopping-cart-2"></i>
    <button @click="goShopping" class="start-shopping-btn">去购物</button>
</div>
<script src="../js/vue.js"></script>
<script src="../js/element-ui/lib/index.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<link rel="stylesheet" href="../js/element-ui/lib/theme-chalk/index.css">
<script>
    var app = new Vue({
        el: '#cart-page',
        data() {
            return {
                cartItems: [],
                userId: 1 // 假设当前用户ID为1
            };
        },
        computed: {
            selectedCount() {
                return this.cartItems.filter(item => item.selected).length;
            },
            totalPrice() {
                return this.cartItems
                    .filter(item => item.selected)
                    .reduce((total, item) => {
                        const price = parseFloat(item.price);
                        const quantity = parseInt(item.quantity);
                        return total + (isNaN(price) || isNaN(quantity)? 0 : price * quantity);
                    }, 0);
            }
        },
        methods: {
            async fetchCartItems() {
                try {
                    const response = await axios.get('/shoppingcarts/items', {
                        params: { userId: this.userId }
                    });
                    if (response.data.code === 20041) {
                        // 假设后端返回的数据结构为[{cartId, userId, productId, quantity, addedAt, categoryId, productNumber, productName, price, stock, stockAlertThreshold, isPublished, createdAt, updatedAt, selected: false}]
                        this.cartItems = response.data.data.map(item => ({
                            ...item,
                            selected: false
                        }));
                    } else {
                        this.$message.error(response.data.msg || '获取购物车失败');
                    }
                } catch (error) {
                    if (error.response) {
                        this.$message.error(`请求失败，状态码: ${error.response.status}，错误信息: ${error.response.data.msg || '无错误信息'}`);
                    } else if (error.request) {
                        this.$message.error('请求未成功发出，请检查网络连接');
                    } else {
                        this.$message.error('发生其他错误，请联系管理员');
                    }
                    console.error('获取购物车失败', error);
                }
            },
            async updateCartItemQuantity(productId, quantity) {
                // 更新购物车项数量的逻辑
            },
            decreaseQuantity(index) {
                const item = this.cartItems[index];
                if (item.quantity > 1) {
                    item.quantity--;
                    this.updateCartItemQuantity(item.productId, item.quantity);
                }
            },
            increaseQuantity(index) {
                const item = this.cartItems[index];
                item.quantity++;
                this.updateCartItemQuantity(item.productId, item.quantity);
            },
            async removeFromCart(productId) {
                try {
                    await axios.delete('/shoppingcarts/remove', {
                        params: {
                            userId: this.userId,
                            productId: productId
                        }
                    });
                    // 更新本地购物车
                    this.cartItems = this.cartItems.filter(item => item.productId !== productId);
                } catch (error) {
                    this.$message.error('删除失败');
                }
            },
            checkout() {
                const selectedItems = this.cartItems.filter(item => item.selected);
                if (selectedItems.length === 0) {
                    this.$message.warning('请选择要结算的商品');
                    return;
                }
                // 结算的逻辑
                console.log('结算:', selectedItems);
                this.$message({
                    type: 'info',
                    message: `结算 ${selectedItems.length} 件商品，总价: ¥${this.totalPrice.toFixed(2)}`
                });
            },
            goToProductDetail(productId) {
                location.href = `products.html?productId=${productId}`;
                console.log('跳转到商品详情页:', productId);
            }
        },
        mounted() {
            this.fetchCartItems();
        }
    });
</script>
</body>
</html>